<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="bom" prop="bomName">
        <el-input v-model="queryParams.bomName" placeholder="请输入bom" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="物料版本" prop="bomVersion">
        <el-input v-model="queryParams.bomVersion" placeholder="请输入物料版本" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['basic:product-bom:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['basic:product-bom:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['basic:product-bom:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="产品名称" align="center" prop="productName"/>
      <el-table-column label="产品编码" align="center" prop="productCode"/>
      <el-table-column label="bom" align="center" prop="bomName"/>
      <el-table-column label="bom版本" align="center" prop="bomVersion"/>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['basic:product-bom:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-s-grid" @click="openChildBomDialog(scope.row)"
                     v-hasPermi="['basic:product-bom:update']">子级bom
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['basic:product-bom:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <ProductBomForm ref="formRef" @success="getList"/>

    <!-- 子级bom对话框 -->
    <el-dialog :title="`${currentBomRow?.productName || ''} - 子级BOM`" :visible.sync="childBomDialogVisible" width="1200px" v-dialogDrag append-to-body>
      <div>
        <el-button type="primary" icon="el-icon-plus" size="small" @click="openChildItemForm()" style="margin-bottom: 10px">新增子级</el-button>

        <el-table v-loading="childItemsLoading" :data="currentBomRow?.items || []" border style="width: 100%" max-height="500px">
          <el-table-column prop="materialName" label="物料名称" align="center" show-overflow-tooltip/>
          <el-table-column prop="materialNo" label="物料编码" align="center" show-overflow-tooltip/>
          <el-table-column prop="materialNumber" label="物料数量" align="center" />
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template v-slot="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="openChildItemForm(scope.row)">编辑</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteChildItem(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeChildBomDialog">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 子级项编辑对话框 -->
    <el-dialog :title="childItemFormTitle" :visible.sync="childItemFormVisible" width="600px" v-dialogDrag append-to-body>
      <el-form ref="childItemFormRef" :model="childItemForm" :rules="childItemFormRules" label-width="100px">
        <el-form-item label="物料" prop="materialId">
          <el-select v-model="childItemForm.materialId" filterable remote :remote-method="remoteMethod" :loading="materialLoading" placeholder="请选择物料编码" style="width: 100%">
            <el-option v-for="item in materialList" :key="item.id" :label="item.materialNo" :value="item.id">
              <span style="float: left">{{ item.materialName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialNo }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料数量" prop="materialNumber">
          <el-input v-model="childItemForm.materialNumber" type="number" placeholder="请输入数量"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="childItemFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveChildItem">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ProductBomApi from '@/api/basic/productbom/index.js';
import * as MaterialApi from '@/api/basic/material/index.js';
import { getDictDatas, getDictDataLabel, DICT_TYPE } from '@/utils/dict';
import ProductBomForm from './ProductBomForm.vue';

export default {
  name: "ProductBom",
  components: {
    ProductBomForm
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品bom列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        productId: null,
        productName: null,
        productCode: null,
        bomName: null,
        bomVersion: null,
        status: null,
        createTime: [],
      },
      // 子级BOM对话框相关
      childBomDialogVisible: false,
      currentBomRow: null,
      childItemsLoading: false,
      // 子级项编辑对话框相关
      childItemFormVisible: false,
      childItemFormTitle: "新增子级项",
      editingChildItemIndex: -1,
      childItemForm: {
        id: null,
        productBomId: null,
        materialId: null,
        materialNumber: 0,
        sort: 0
      },
      childItemFormRules: {
        materialId: [{ required: true, message: '请选择物料', trigger: 'change' }],
        materialNumber: [{ required: true, message: '请输入物料数量', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序号', trigger: 'blur' },
              { type: 'number', min: 0, message: '排序号不能小于0', trigger: 'blur' }]
      },
      // 物料列表相关
      materialList: [],
      materialLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await ProductBomApi.getProductBomPage(this.queryParams);
        // 确保每个BOM行都有items数组
        this.list = res.data.list.map(item => ({
          ...item,
          items: item.items || []
        }));
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除产品bom编号为"' + id + '"的数据项?')
      try {
        await ProductBomApi.deleteProductBom(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除产品bom */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await ProductBomApi.deleteProductBomList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有产品bom数据项?');
      try {
        this.exportLoading = true;
        const data = await ProductBomApi.exportProductBomExcel(this.queryParams);
        this.$download.excel(data, '产品bom.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    /** 打开子级BOM对话框 */
    async openChildBomDialog(row) {
      this.currentBomRow = { ...row };
      this.childBomDialogVisible = true;

      // 如果当前行没有items数组，初始化一个空数组
      if (!this.currentBomRow.items) {
        this.currentBomRow.items = [];
      }
    },

    /** 关闭子级BOM对话框 */
    closeChildBomDialog() {
      this.childBomDialogVisible = false;
    },

    /** 打开子级项编辑对话框 */
    openChildItemForm(item = null) {
      // 重置表单
      this.childItemForm = {
        productBomId: this.currentBomRow.id,
        materialId: null,
        materialNumber: '', // 不设置默认值为0
        sort: 0
      };

      if (item) {
        // 编辑模式
        this.childItemFormTitle = "编辑子级项";
        this.editingChildItemIndex = this.currentBomRow.items.findIndex(i => i.id === item.id);
        if(item.materialName){
          this.remoteMethod(item.materialNo);
        }
        this.childItemForm = { ...item };
      } else {
        // 新增模式
        this.childItemFormTitle = "新增子级项";
        this.editingChildItemIndex = -1;
      }

      // 弹出对话框前默认搜索前20条物料
      this.remoteMethod('');

      this.childItemFormVisible = true;
    },
    /** 物料数量输入框获取焦点时的处理函数 */
    onMaterialNumberFocus() {
      // 如果当前值为0，则清空
      if (this.childItemForm.materialNumber === 0 || this.childItemForm.materialNumber === '0') {
        this.childItemForm.materialNumber = '';
      }
    },

    /** 保存子级项 */
    async saveChildItem() {
      try {
        await this.$refs.childItemFormRef.validate();

        if (this.editingChildItemIndex >= 0) {
          // 编辑现有项
          this.currentBomRow.items[this.editingChildItemIndex] = { ...this.childItemForm };
        } else {
          // 新增项
          this.currentBomRow.items.push({ ...this.childItemForm });
        }

        this.$modal.msgSuccess("保存成功");
        this.childItemFormVisible = false;
      } catch (error) {
        // 校验失败时会自动提示错误信息
      }
    },

    /** 删除子级项 */
    async deleteChildItem(row) {
      await this.$modal.confirm('是否确认删除该项?');
      const index = this.currentBomRow.items.findIndex(item => item.id === row.id);
      if (index !== -1) {
        this.currentBomRow.items.splice(index, 1);
        this.$modal.msgSuccess("删除成功");
      }
    },

    /** 保存全部子级项 */
    async saveChildBomItems() {
      try {
        // 更新当前行的数据
        const updatedRow = {
          ...this.currentBomRow
        };

        // 调用产品BOM的更新接口，保存子级数据
        await ProductBomApi.updateProductBom(updatedRow);

        this.$modal.msgSuccess("保存成功");
        this.closeChildBomDialog();
        // 刷新列表
        await this.getList();
      } catch (error) {
        this.$modal.msgError("保存失败：" + (error.message || '未知错误'));
      }
    },

    /** 物料远程搜索方法 */
    async remoteMethod(query) {
      this.materialLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 20,
          materialNo: query
        };
        const res = await MaterialApi.getMaterialPage(params);
        this.materialList = res.data.list;
      } catch (error) {
        console.error('获取物料列表失败:', error);
        this.materialList = [];
      } finally {
        this.materialLoading = false;
      }
    },

    /** 根据物料ID获取物料名称 */
    getMaterialName(materialId) {
      if (!materialId) return '';
      const material = this.materialList.find(item => item.id === materialId);
      return material ? material.materialName : '';
    },

    /** 检查数组是否为空 */
    isEmpty(arr) {
      return !arr || arr.length === 0;
    }
  }
};
</script>
